package cn.stylefeng.guns.modular.packreview.service.impl;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.base.shiro.ShiroUser;
import cn.stylefeng.guns.modular.goodsMcJst.model.params.GoodsMcJstParam;
import cn.stylefeng.guns.modular.goodsMcJst.model.result.GoodsMcJstResult;
import cn.stylefeng.guns.modular.goodsMcJst.service.GoodsMcJstService;
import cn.stylefeng.guns.modular.packreview.entity.*;
import cn.stylefeng.guns.modular.packreview.mapper.ExpressDeliveryWaybillMapper;
import cn.stylefeng.guns.modular.packreview.model.params.ExpressDeliveryWaybillParam;
import cn.stylefeng.guns.modular.packreview.model.params.PackReviewDetailsParam;
import cn.stylefeng.guns.modular.packreview.model.params.PickingListParam;
import cn.stylefeng.guns.modular.packreview.model.result.ExpressDeliveryWaybillResult;
import cn.stylefeng.guns.modular.packreview.model.result.PickingListResult;
import  cn.stylefeng.guns.modular.packreview.service.ExpressDeliveryWaybillService;
import cn.stylefeng.guns.modular.packreview.service.PackReviewDetailsService;
import cn.stylefeng.guns.modular.packreview.service.PackReviewService;
import cn.stylefeng.guns.modular.packreview.service.PickingListService;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import static cn.stylefeng.guns.modular.location.excel.ExcelUtils.getCellValue;
import static cn.stylefeng.guns.sys.core.shiro.ShiroKit.getUser;

/**
 * <p>
 * 快递运输单 服务实现类
 * </p>
 *
 * @author wp
 * @since 2025-07-29
 */
@Service
public class ExpressDeliveryWaybillServiceImpl extends ServiceImpl<ExpressDeliveryWaybillMapper, ExpressDeliveryWaybill> implements ExpressDeliveryWaybillService {

    @Autowired
    private PickingListService pickingListService;
    @Autowired
    private PackReviewService packReviewService;
    @Autowired
    private PackReviewDetailsService packReviewDetailsService;
    @Autowired
    private GoodsMcJstService goodsMcJstService;
    @Override
    public void add(ExpressDeliveryWaybillParam param){
        ExpressDeliveryWaybill entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(ExpressDeliveryWaybillParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(ExpressDeliveryWaybillParam param){
        ExpressDeliveryWaybill oldEntity = getOldEntity(param);
        ExpressDeliveryWaybill newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public ExpressDeliveryWaybillResult findBySpec(ExpressDeliveryWaybillParam param){
        return null;
    }

    @Override
    public List<ExpressDeliveryWaybillResult> findListBySpec(ExpressDeliveryWaybillParam param){
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(ExpressDeliveryWaybillParam param,String condition){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param,condition);
        return LayuiPageFactory.createPageInfo(page);
    }

    @Override
    public ResponseData getExceldata(MultipartFile file, ExpressDeliveryWaybillParam expressDeliveryWaybillParam, ResponseData data) throws IOException {
        String fileName = file.getOriginalFilename();

        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            data.setMessage("上传文件格式不正确");
            data.setSuccess(false);
        }
        boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }
        InputStream is = file.getInputStream();
        Workbook wb = null;
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }
        Sheet sheet = wb.getSheetAt(0);

        List<ExpressDeliveryWaybillExcelItem> list = new ArrayList<ExpressDeliveryWaybillExcelItem>();
        for (int r = 1; r <= sheet.getLastRowNum()+1; r++) {
            Row row = sheet.getRow(r);
            if (row == null){
                continue;
            }

            ExpressDeliveryWaybillExcelItem expressDeliveryWaybillExcelItem = new ExpressDeliveryWaybillExcelItem();
            String trackNumber = getCellValue(row.getCell(0));//运单号
            if (StringUtils.isNotEmpty(trackNumber)){
                trackNumber = trackNumber.replace("`", "");
            }
            expressDeliveryWaybillExcelItem.setTrackNumber(trackNumber);

            String sendTime = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(1));//发货时间
            expressDeliveryWaybillExcelItem.setSendOutTime(sendTime);

            String  goodsName = getCellValue(row.getCell(2));//商品名称
            expressDeliveryWaybillExcelItem.setGoodsName(goodsName);

            String pickNumber = getCellValue(row.getCell(3));//拣选单号
            if (StringUtils.isNotEmpty(pickNumber)){
                pickNumber = pickNumber.replace("`", "");
            }
            expressDeliveryWaybillExcelItem.setPickNumber(pickNumber);

            String mcGoodsCode = getCellValue(row.getCell(4));//商品条码
            if (StringUtils.isNotEmpty(mcGoodsCode)){
                mcGoodsCode = mcGoodsCode.replace("`", "");
            }else {
                return ResponseData.error("猫超码不能为空");
            }
            expressDeliveryWaybillExcelItem.setMcGoodsCode(mcGoodsCode);

            String goodsCount = getCellValue(row.getCell(5));//发货数量
            expressDeliveryWaybillExcelItem.setSendGoodsCount(Integer.valueOf(goodsCount));

            list.add(expressDeliveryWaybillExcelItem);
        }

        ShiroUser user = getUser();
        //主表信息
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


        Collection<ExpressDeliveryWaybillExcelItem> values = list.stream()
                .collect(Collectors.toMap(
                        companyVo -> companyVo.getPickNumber() + "-" + companyVo.getTrackNumber() + "-" + companyVo.getMcGoodsCode()+"-" + companyVo.getGoodsName(), // 使用 id 和 code 作为 key
                        companyVo -> companyVo, // 保留 CompanyVo 对象
                        (existing, replacement) -> existing // 如果有重复的 id，保留已有的对象
                )).values();


        List<ExpressDeliveryWaybillExcelItem> uniqueList = new ArrayList<>(values); // 从Map中提取值列表作为结果列表


        // 保存主表信息
        List<ExpressDeliveryWaybill> expressDeliveryWaybillList = new ArrayList<>();
        for (ExpressDeliveryWaybillExcelItem expressDeliveryWaybillExcelItem : uniqueList) {
            String pickNumber = expressDeliveryWaybillExcelItem.getPickNumber();
            String trackNumber = expressDeliveryWaybillExcelItem.getTrackNumber();
            if (StringUtils.isEmpty(pickNumber) || StringUtils.isEmpty(trackNumber)){
                return ResponseData.error("请上传正确的excel文件:拣选单号和运单号不能为空");
            }
            if(!(pickNumber.contains("PKTNA") && trackNumber.contains("SF"))){
                return ResponseData.error("请上传正确的excel文件:拣选单号必须包含PKTNA,运单号必须包含SF");
            }
            ExpressDeliveryWaybill expressDeliveryWaybill = new ExpressDeliveryWaybill();
            BeanUtils.copyProperties(expressDeliveryWaybillExcelItem, expressDeliveryWaybill);

            expressDeliveryWaybill.setPutCustomerId(expressDeliveryWaybillParam.getPutCustomerId());
            expressDeliveryWaybill.setWarehouseId(expressDeliveryWaybillParam.getWarehouseId());
            expressDeliveryWaybill.setDeptId(user.getDeptId());
            expressDeliveryWaybill.setCreateBy(user.getName());//创建人
            expressDeliveryWaybill.setCreateTime(new Date());
            expressDeliveryWaybillList.add(expressDeliveryWaybill);

        }
        this.saveBatch(expressDeliveryWaybillList,500);
        // 生成复核作业单
        Map<String, ExpressDeliveryWaybillExcelItem> trackNumberMap = list.stream()
                .collect(Collectors.toMap(ExpressDeliveryWaybillExcelItem::getTrackNumber,
                        Function.identity(),
                        (existing, replacement) -> existing)
                ); // 使用自定义的合并函数来保持第一个遇到的元素（如果有重复的track number）

        List<ExpressDeliveryWaybillExcelItem> uniqueListWork = new ArrayList<>(trackNumberMap.values()); // 从Map中提取值列表作为结果列表

        List<PackReview> packReviewList = new ArrayList<>();
        for (ExpressDeliveryWaybillExcelItem expressDeliveryWaybillExcelItem : uniqueListWork) {
            PackReview packReview = new PackReview();
            String sendOutTime = expressDeliveryWaybillExcelItem.getSendOutTime();
            String replace = sendOutTime.replace("T", " ");
            try {
                Date parse = simpleDateFormat.parse(replace);
                packReview.setSendOutTime(parse);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            packReview.setTrackNumber(expressDeliveryWaybillExcelItem.getTrackNumber());
            packReview.setPickNumber(expressDeliveryWaybillExcelItem.getPickNumber());
            packReview.setPutCustomerId(expressDeliveryWaybillParam.getPutCustomerId());
            PickingListParam pickingListParam = new PickingListParam();
            pickingListParam.setPickNumber(expressDeliveryWaybillExcelItem.getPickNumber());
            String pickType = pickingListService.findPickTypeByPickNumber(expressDeliveryWaybillExcelItem.getPickNumber());
            packReview.setOrderType(pickType);
            packReview.setWarehouseId(expressDeliveryWaybillParam.getWarehouseId());
            packReview.setDeptId(user.getDeptId());
            packReview.setCreateBy(user.getName());//创建人
            packReview.setCreateTime(new Date());
            packReviewService.insertPackReview(packReview);
//            packReviewList.add(packReview);

        }
//        packReviewService.saveBatch(packReviewList,200);
        //快递单生成复核作业明细

        for (ExpressDeliveryWaybillExcelItem waybillExcelItem : list) {
            List<PackReviewDetails> packReviewDetailsList = new ArrayList<>();
            // 快递单中的发货数量
            Integer sendGoodsCount = waybillExcelItem.getSendGoodsCount();
            String pickType = pickingListService.findPickTypeByPickNumber(waybillExcelItem.getPickNumber());

            GoodsMcJstParam goodsMcJstParam = new GoodsMcJstParam();
            goodsMcJstParam.setMcGoodsCode(waybillExcelItem.getMcGoodsCode());
//            goodsMcJstParam.setJstGoodsName(waybillExcelItem.getGoodsName());
            List<GoodsMcJstResult> listBySpec = goodsMcJstService.findListBySpec(goodsMcJstParam);
            if (listBySpec.size() == 0){
                packReviewService.deleteByTrackNumber(waybillExcelItem.getTrackNumber());
                continue;
            }
            for (GoodsMcJstResult goodsMcJstResult : listBySpec) {
                PackReviewDetails packReviewDetails = new PackReviewDetails();
                packReviewDetails.setGoodsNum(goodsMcJstResult.getNsCode());
                packReviewDetails.setTrackNumber(waybillExcelItem.getTrackNumber());
                packReviewDetails.setGoodsName(goodsMcJstResult.getJstGoodsName());
                packReviewDetails.setGoodsCode(goodsMcJstResult.getJstGoodsCode());
                packReviewDetails.setMcGoodsCode(goodsMcJstResult.getMcGoodsCode());
                packReviewDetails.setGoodsCount(goodsMcJstResult.getGoodsCount() * sendGoodsCount);

                packReviewDetails.setCreateBy(user.getName());//创建人
                packReviewDetails.setCreateTime(new Date());

                packReviewDetails.setPickType(pickType);

//                packReviewDetailsList.add(packReviewDetails);
//                packReviewDetailsService.save(packReviewDetails);
                packReviewDetailsService.insertPackReviewDetails(packReviewDetails);
            }

//            packReviewDetailsService.saveBatch(packReviewDetailsList,200);
        }
//        packReviewDetailsService.saveBatch(packReviewDetailsList,200);
        data.setSuccess(true);
        data.setMessage("导入成功");
        return data;
    }

    private Serializable getKey(ExpressDeliveryWaybillParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private ExpressDeliveryWaybill getOldEntity(ExpressDeliveryWaybillParam param) {
        return this.getById(getKey(param));
    }

    private ExpressDeliveryWaybill getEntity(ExpressDeliveryWaybillParam param) {
        ExpressDeliveryWaybill entity = new ExpressDeliveryWaybill();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }


    public static void main(String[] args) {
        String str = "123`456";
        System.out.println(str.replace("`", ""));
    }
}
